package com.gang.music.system.controller;

import com.gang.music.common.AjaxResult;
import com.gang.music.core.annotation.Before;
import com.gang.music.core.intercept.LoginValidator;
import com.gang.music.core.intercept.RequestValidator;
import com.gang.music.core.shiro.ShiroKit;
import com.gang.music.core.shiro.ShiroUser;
import com.gang.music.system.entity.User;
import com.smallchill.core.toolbox.captcha.Captcha;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 前台登录
 */
@Controller
@RequestMapping(value = "/login")
public class LoginController extends BaseController {

	@Before(RequestValidator.class)
	@RequestMapping(method = RequestMethod.GET)
	public String login(HttpServletRequest request, HttpServletResponse response) {
		return "web/login";
	}

	@Before(LoginValidator.class)
	@ResponseBody
	@RequestMapping(method = RequestMethod.POST)
	public AjaxResult login(User user, String imgCode, HttpServletRequest request,
			HttpServletResponse response, Boolean rememberMe) {
		
		if (!Captcha.validate(request, response, imgCode)) {
			return error("验证码错误");
		}
		
		Subject subject = ShiroKit.getSubject();
		UsernamePasswordToken token = 
				new UsernamePasswordToken(user.getLoginName(), user.getPlainPassword());
		if(rememberMe != null) {
			token.setRememberMe(true);
		}
		try {
			subject.login(token);
			Session session = ShiroKit.getSession();
			ShiroUser shiroUser = (ShiroUser) subject.getPrincipal();
			session.setAttribute("shiroUser", shiroUser);
			return success();
		} catch (UnknownAccountException e) {
			e.printStackTrace();
			return error("账号或密码错误!");
		} catch (IncorrectCredentialsException e) {
			e.printStackTrace();
			return error("账号或密码错误!");
		} catch (ExcessiveAttemptsException e) {
			return error("登录失败多次,账号已被锁定.请在"+ e.getMessage() + "后再试!");
		}
	}
}
